import pygame
import sys
from Fire import Fire
from Enemy import Enemy
import time
from Score import Score
from Gun import Gun
from Statisctics import Statistic
def events(gun,screen,bullets):

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            #программируем нажатие определенной клавиши

            if event.key == pygame.K_RIGHT:
                gun.mright = True
            if event.key == pygame.K_LEFT:
                gun.mleft = True
            if event.key == pygame.K_SPACE:
                new_bullet = Fire(gun=gun,screen=screen)
                bullets.add(new_bullet)
        elif event.type == pygame.KEYUP:
            #программируем то, что клавишу отпустили

            if event.key == pygame.K_RIGHT:
                gun.mright = False
            if event.key == pygame.K_LEFT:
                gun.mleft = False

def draw(screen,bg_color,gun,enemys,bullets,stats,score):
    "Обновление экрана"

    screen.fill(bg_color)
    score.show()
    for bullet in bullets.sprites():
        bullet.drawBullet()
    gun.visualise()
    enemys.draw(screen)
    pygame.display.flip()

def gun_killed(statisctic, screen, gun, enemys, bullets, score):
    'Коллизия для пушки + отнимание жизней'
    if statisctic.lives <= 0:
        statisctic.run_game = False
        sys.exit()
    else:
        statisctic.lives -= 1
        score.lives_img()
        enemys.empty()
        bullets.empty()
        create_army(screen, enemys)
        gun.gun_alive()
        time.sleep(1)

def lose_check(statisctic, screen, gun, enemys, bullets, score):
    screen_rect = screen.get_rect()
    for e in enemys.sprites():
        if e.rect.bottom >= screen_rect.bottom:
            gun_killed(statisctic, screen, gun, enemys, bullets, score)
            break

def update_enemys(statisctic, screen,gun, enemys,bullets, score):
    "Рисует движение кразаябр"
    enemys.update()
    if pygame.sprite.spritecollideany(gun, enemys):
        gun_killed(statisctic,screen,gun,enemys,bullets, score)
    lose_check(statisctic, screen, gun, enemys, bullets, score)

def update_bullets(screen,stats, score, enemys, bullets):
    "удаление пуль за пределами экрана"
    bullets.update()
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    collision = pygame.sprite.groupcollide(bullets, enemys, True, True)
    if collision:
        for e in collision.values():
            stats.score += 1 * len(e)
        high_core(stats,score)
        score.text_image_score()
        score.lives_img()
    if len(enemys) == 0:
        bullets.empty()
        create_army(screen,enemys)

def create_army(screen,enemys):
    enemy = Enemy(screen)
    enemy_width = enemy.rect.width
    enemy_height = enemy.rect.height
    enemy_number_x = int((764 - 2 * enemy_width) / enemy_width)
    enemy_number_y = int(((800 - 128) - 2 * enemy_height) / enemy_height)

    for er in range(enemy_number_y - 4):
        for e in range(enemy_number_x):
            enemy = Enemy(screen)
            enemy.x = enemy_width + enemy_width * e
            enemy.y = enemy_height + enemy_height * er
            enemy.rect.x = enemy.x
            enemy.rect.y = enemy_height + enemy.rect.height * er
            enemys.add(enemy)

def high_core(stats, score):
    if stats.score > stats.record:
        stats.record = stats.score
        score.image_record()
        with open('record.txt', 'w') as f:
            f.write(str(stats.record))